package com.example.parking.application;

import com.example.parking.domain.model.ParkingSpace;
import com.example.parking.domain.repository.ParkingSpaceRepository;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ParkingSpaceService {
    private final ParkingSpaceRepository parkingSpaceRepository;

    public ParkingSpaceService(ParkingSpaceRepository parkingSpaceRepository) {
        this.parkingSpaceRepository = parkingSpaceRepository;
    }

    @Cacheable(cacheNames = "spaces:byLot", key = "#lotCode")
    public List<ParkingSpace> listByLot(String lotCode) {
        return parkingSpaceRepository.findByLotCode(lotCode);
    }

    public ParkingSpace getById(Long id) {
        return parkingSpaceRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("space not found"));
    }

    @Transactional
    @CacheEvict(cacheNames = {"spaces:byLot"}, key = "#space.lotCode")
    public ParkingSpace create(ParkingSpace space) {
        if (parkingSpaceRepository.existsByLotCodeAndSpaceCode(space.getLotCode(), space.getSpaceCode())) {
            throw new IllegalArgumentException("space exists");
        }
        return parkingSpaceRepository.save(space);
    }

    @Transactional
    @CacheEvict(cacheNames = {"spaces:byLot"}, key = "#incoming.lotCode")
    public ParkingSpace update(Long id, ParkingSpace incoming) {
        ParkingSpace space = getById(id);
        space.setStatus(incoming.getStatus());
        return parkingSpaceRepository.save(space);
    }

    @Transactional
    @CacheEvict(cacheNames = {"spaces:byLot"}, allEntries = true)
    public void delete(Long id) {
        parkingSpaceRepository.deleteById(id);
    }
}


